/***************************************************************************
 *   Copyright (C) 2008 by JBox systems
 *   gabi@shaargiora.co.il
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 ***************************************************************************/

#pragma once

#include <QtNetwork>
#include <QHttp>
#include <QByteArray>
#include <QFile>
#include <QObject>
#include <string>
#include<QHttpResponseHeader>

/**
	File downloader.

	HTTP and FTP file downloader.
*/
//TODO: not finished yet, hands off.
class Downloader : public QObject {
	Q_OBJECT

	public:
		enum Scheme { HTTP, FTP };

		std::map<std::string, int> scheme_lookup;

		Downloader(std::string source, std::string destination, QObject *parent = 0);

	private slots:

		/**
			Start downloading file.
		*/
		void downloadFile();

		/**
			Download file over HTTP.
		*/
		void downloadHttpFile();

		/**
			Cancel download file.

			This is used for both HTTP and FTP.
		*/
		void cancelDownload();

		/**
		*/
		void httpRequestFinished(int requestId, bool error);

		/**
		*/
		void readResponseHeader(const QHttpResponseHeader &responseHeader);

		/**
			Download file over FTP.
		*/
		void downloadFtpFile();

		/**
		*/
		void ftpCommandFinished(int commandId, bool error);

		/**
		*/
		void updateDataTransferProgress(qint64 readBytes, qint64 totalBytes);

		/**
			Open destination file for writing.

			@return success
		*/
		bool openDownloadFile();

	private:

		QHttp *http; ///
		QFtp *ftp; ///
		QFile *file; ///
		QUrl *url; ///
		QByteArray buffer;
		int httpGetId; ///
		bool httpRequestAborted; ///
		std::string destination; ///

		/**
			Ensure existance of local destination folder.
		*/
		void validatePath();

	private slots:

		void writeToLocalFile(const QHttpResponseHeader &resp);

	signals:

		/**
		*/
		void dataReadProgress(int, int);

		/**
		*/
		void downloadFinished(bool);
};
